import 'package:bpb/framework/base/base_page.dart';
import 'package:bpb/framework/custom/ext_widget/widget_util.dart';
import 'package:bpb/framework/utils/date_utils.dart';
import 'package:bpb/framework/utils/sized_box_util.dart';
import 'package:bpb/pages/home/home_controller.dart';
import 'package:bpb/routers/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:table_calendar/table_calendar.dart';
import '../../common/CommonData.dart';

class HomePage extends BasePage<HomeController> {


  @override
  Widget build(BuildContext context) {


    var kkToday = DateTime.now();
    var kkFirstDay = DateTime(kkToday.year, kkToday.month - 3, kkToday.day);
    var kkLastDay = DateTime(kkToday.year, kkToday.month + 3, kkToday.day);

    return Scaffold(
      backgroundColor: Color(0xffF5F3F1),
      body: Column(
        children: [
          sb.h(MediaQuery.of(context).padding.top),
          Row(
            children: [
              sb.w(15.w),
              Text("${DateUtil.MMM_D.format(kkToday)}", style: GoogleFonts.poppins(fontWeight: FontWeight.w600, fontSize: 20.sp, color: Colors.black)),
              Spacer(),
              Row(
                children: [
                  Image.asset("images/icon_trend.png", width: 33.w).prop(
                    onTap: () {
                      Get.toNamed(AppPage.ROUTER_HISTRY);
                    },
                  ),
                  sb.w(12.w),
                  Image.asset("images/icon_setting.png", width: 33.w).prop(onTap: (){

                    Get.toNamed(AppPage.ROUTER_SETTING);
                  }),
                ],
              ),
              sb.w(15.w),
            ],
          ),
          sb.h(26.h),
          Obx(() {


            var allMapCountDatas = controller.dataMaps.value;

            return Container(
              child: TableCalendar(
                firstDay: kkFirstDay,
                lastDay: kkLastDay,
                headerVisible: false,
                daysOfWeekVisible: true,
                pageJumpingEnabled: true,
                pageAnimationEnabled: true,
                sixWeekMonthsEnforced: true,
                shouldFillViewport: false,
                weekNumbersVisible: false,
                daysOfWeekStyle: DaysOfWeekStyle(
                  weekdayStyle: TextStyle(
                    color: Colors.black87,
                    fontWeight: FontWeight.bold,
                    fontSize: 12.sp,
                  ),
                  weekendStyle: TextStyle(
                    color: Colors.redAccent,
                    fontWeight: FontWeight.bold,
                  ),
                  dowTextFormatter: (date, locale) {
                    // 自定义显示内容，如改成中文或缩写
                    return DateFormat.E(locale).format(date); // 默认缩写，如 Mon, Tue
                  },
                ),

                calendarStyle: CalendarStyle(
                  // Use `CalendarStyle` to customize the UI
                  outsideDaysVisible: false,
                  markerSize: 4.w,
                  markerDecoration: BoxDecoration(color: Color(0xff5DB075), shape: BoxShape.circle),
                  defaultTextStyle: GoogleFonts.poppins(
                    fontWeight: FontWeight.w500,
                    fontSize: 16.sp,
                    color: Color(0xff333333)
                  ),

                ),
                eventLoader: (day) {
                  String dft = DateUtil.DF_YMD.format(day);
                  List<dynamic>? realDatas = allMapCountDatas[dft];
                  if (null == realDatas || realDatas.isEmpty) {
                    return [];
                  } else {
                    return [{}]; //无论有多少按一个点处理
                  }
                },
                focusedDay: controller.focusedDay.value,
                calendarFormat: controller.calendarFormat.value,
                // calendarFormat: CalendarFormat.week,
                selectedDayPredicate: (day) {
                  return isSameDay(controller.selectedDay.value, day);
                },
                onDaySelected: (selectedDay, focusedDay) {
                  if (!isSameDay(controller.selectedDay.value, selectedDay)) {
                    controller.selectedDay.value = selectedDay;
                    controller.focusedDay.value = focusedDay;
                  }
                  debugPrint("onDaySelected--->");
                  controller.onDateSelected(selectedDay);
                },
                onFormatChanged: (format) {
                  if (controller.calendarFormat != format) {
                    controller.calendarFormat.value = format;
                  }
                  debugPrint("onFormatChanged--->");
                },
                onPageChanged: (focusedDay) {
                  controller.focusedDay.value = focusedDay;
                  debugPrint("onPageChanged---> ${focusedDay}");
                  controller.onPageChanged(focusedDay);
                },
              ),
            );
          }),
          Column(
            children: [
              Obx(() {
                if (controller.calendarFormat.value == CalendarFormat.week) {
                  return Icon(Icons.keyboard_arrow_down, size: 20.w);
                } else {
                  return Icon(Icons.keyboard_arrow_up, size: 20.w);
                }
              }),
            ],
          ).prop(
            onTap: () {
              // controller.calendarFormat.value=
              if (controller.calendarFormat.value == CalendarFormat.week) {
                controller.calendarFormat.value = CalendarFormat.month;
              } else {
                controller.calendarFormat.value = CalendarFormat.week;
              }
            },
          ),
          Container(width: double.infinity, height: 1.h, color: Color(0xffDADADA), margin: EdgeInsets.only(left: 15.w, right: 15.w)),
          Expanded(
            child: SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(bottom: 50.h),
                child: Obx(() {
                  if (controller.bloodInfos.value.isEmpty) {
                    return Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(child: Image.asset("images/icon_no_result.png"), margin: EdgeInsets.only(left: 37.w, right: 37.w)),
                        sb.w(150.w),
                      ],
                    );
                  }

                  List<Widget> bloodItems =
                      controller.bloodInfos.value.map((data) {
                        //每一个血压数据
                        int sys = (double.parse(data["sys"].toString())).toInt();
                        int dia = (double.parse(data["dia"].toString())).toInt();
                        int pulse = (double.parse(data["pulse"].toString())).toInt();

                        String recordtime = data["recordTime"];
                        DateTime dt = DateUtil.DF_YMDHMS.parse(recordtime);
                        String showTime = DateUtil.DD_MM_YY_HH_MM.format(dt);

                        List<String> levelRange = CommonData.getBloodPressureLevel(sys, dia);
                        String level = levelRange[0];

                        //    Color bgColor = const Color(0x260F66EB);
                        //     Color textColor = const Color(0xff154DA2);
                        List<Color> colors = CommonData.getColorByLevel(level);
                        Color bgCoolor = colors[0];
                        Color textColor = colors[1];

                        return Container(
                          margin: EdgeInsets.only(top: 10.h),
                          padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 20.h, bottom: 20.h),
                          width: double.infinity,
                          height: 148.h,
                          decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(15.r)), color: Color(0xfffbfbfb)),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Text("${showTime}", style: GoogleFonts.poppins(fontSize: 14.sp, fontWeight: FontWeight.w400, color: Color(0xff747474))),
                                  Spacer(),

                                  Offstage(
                                    offstage: true,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Container(
                                          decoration: BoxDecoration(color: bgCoolor, borderRadius: BorderRadius.circular(50.r)),
                                          padding: EdgeInsets.only(top: 6.h, bottom: 6.h),
                                          child: Row(
                                            children: [
                                              sb.w(12.w),
                                              ClipOval(child: Container(width: 10.w, height: 10.w, color: textColor)),
                                              sb.w(4.w),
                                              Container(child: Text("${level}", style: GoogleFonts.poppins(fontSize: 12.sp, fontWeight: FontWeight.w500, color: textColor))),
                                              sb.w(12.w),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),


                                ],
                              ),
                              sb.h(5.h),
                              Row(
                                children: [
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      height: 58.h,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text("SYS", style: GoogleFonts.poppins(fontWeight: FontWeight.w500, color: Color(0xff181920), fontSize: 12.sp, height: 1.2)),
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              Text("${sys}", style: GoogleFonts.poppins(fontSize: 28.sp, fontWeight: FontWeight.w600, color: Color(0xff181920))),
                                              Text(" mmHg", style: GoogleFonts.poppins(fontWeight: FontWeight.w400, fontSize: 12.sp, color: Color(0xff181920), height: 2)),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      height: 58.h,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text("DIA", style: GoogleFonts.poppins(fontWeight: FontWeight.w500, color: Color(0xff181920), fontSize: 12.sp, height: 1.2)),
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              Text("${dia}", style: GoogleFonts.poppins(fontSize: 28.sp, fontWeight: FontWeight.w600, color: Color(0xff181920))),
                                              Text(" mmHg", style: GoogleFonts.poppins(fontWeight: FontWeight.w400, fontSize: 12.sp, color: Color(0xff181920), height: 2)),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      height: 58.h,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            children: [
                                              Icon(Icons.favorite, color: Colors.red, size: 14),
                                              Text("Pulse", style: GoogleFonts.poppins(fontWeight: FontWeight.w500, color: Color(0xff181920), fontSize: 12.sp, height: 1.2)),
                                            ],
                                          ),
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.end,
                                            children: [
                                              Text("${pulse}", style: GoogleFonts.poppins(fontSize: 28.sp, fontWeight: FontWeight.w600, color: Color(0xff181920))),
                                              Text(" bpm", style: GoogleFonts.poppins(fontWeight: FontWeight.w400, fontSize: 12.sp, color: Color(0xff181920), height: 2)),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ).prop(onTap: () async {

                            debugPrint("click item  ===>>>  ${data}");
                            await Get.toNamed(AppPage.ROUTER_ADD,arguments: {"data":data});
                            debugPrint("回来之后刷新");

                            controller.onDeleteRefresh();

                          }),
                        );

                      }).toList();

                  return Container(margin: EdgeInsets.only(left: 15.w, right: 15.w), child: Column(children: bloodItems));
                }),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: ClipOval(
        child: Container(
          width: 50.w,
          height: 50.w,
          color: Color(0xff5DB075),
          child: Icon(Icons.add, color: Colors.white, size: 34.w).prop(
            onTap: () async {
              debugPrint("Click add");
              await Get.toNamed(AppPage.ROUTER_ADD);
              controller.initLoad(defaultDate:controller.pinDate);//刷新当前页面的数据
            },
          ),
        ),
      ),
    );
  }

}
